package org.xx.armory.netty;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * 输出{@literal 404 Not Found}消息的处理器。
 *
 * <p>
 * 此处理器需要放在其它输入处理器的后面，如果没有任何输入处理器可以处理响应，那么使用此处理器输出{@literal 404 Not Found}响应。
 * </p>
 *
 * @author Haart
 */
@Sharable
public final class NotFoundHandler
        extends ChannelInboundHandlerAdapter
        implements ChannelInboundHandler {
    @SuppressWarnings("unused")
    private Logger logger = LoggerFactory.getLogger(NotFoundHandler.class);

    /**
     * {@inheritDoc}
     */
    @Override
    public final void channelRead(
            ChannelHandlerContext ctx,
            Object msg
    )
            throws Exception {
        final FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND);
        response.headers().add(CONTENT_LENGTH, 0);
        ctx.writeAndFlush(response);
    }
}
